package com.turing.orm.handler;

import com.baomidou.mybatisplus.extension.plugins.handler.TableNameHandler;
import com.turing.common.util.SnowFlakeUtil;

/**
  * @ClassName 按id取模分表处理器
  * @Description    
  * @Update T
  * @Date 2022/11/8 14:04
  */
public class DateTableNameParser implements TableNameHandler {

    //使用ThreadLocal防止多线程相互影响
    private static ThreadLocal<Long> taskSn = new ThreadLocal<Long>();

    public static void setTaskSn(Long idValue) {
        taskSn.set(idValue);
    }

    @Override
    public String dynamicTableName(String sql, String tableName) {
        Long val = taskSn.get();
        if (val == null) {
            // do nothing
            return tableName;
        } else {
            String suffix = SnowFlakeUtil.monthBySnowId(val);
            //这里清除ThreadLocal的值，防止线程复用出现问题
            taskSn.set(null);
            return tableName + "_" + suffix;
        }
    }

}